﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Scheduling.Models.Interfaces;
using Scheduling.Models.Repos.Database.Objects;
using Scheduling.Models.Helpers;

namespace Scheduling.Models.Repos.Database
{
    public class DatabaseCourseInstanceLoader : ICourseInstanceLoader
    {

        public List<CourseInstance> GetCourseInstances()
        {
            var db = DBContext.Create();
            var q = from ci in db.CourseInstances
                    join c in db.Courses on ci.CourseID equals c.ID
                    select new { ci, c };
            return LinqHelper.GenericMap<CourseInstance>(q, "ci", "c>Course");
        }

        public bool CourseInstanceExists(int CourseInstanceID)
        {
            var db = DBContext.Create();
            return (from ci in db.CourseInstances where CourseInstanceID == ci.ID select ci).Count() > 0;
        }

        public CourseInstance GetCourseInstance(int CourseInstanceID)
        {
            var db = DBContext.Create();
            var q = from ci in db.CourseInstances
                    join c in db.Courses on ci.CourseID equals c.ID
                    where ci.ID == CourseInstanceID
                    select new { ci, c };
            if (q.Count() > 0)
                return LinqHelper.GenericMap<CourseInstance>(q, "ci", "c>Course").First();
            else
                return null;

        }

        public List<CourseInstance> GetCourseInstancesByCourseID(string SearchCourseID)
        {
            var db = DBContext.Create();
            var q = from ci in db.CourseInstances
                    join c in db.Courses on ci.CourseID equals c.ID
                    where c.ID == SearchCourseID
                    select new { ci, c };
            return LinqHelper.GenericMap<CourseInstance>(q, "ci", "c>Course");
        }


        public List<CourseInstance> GetCourseInstancesByQuery(string Query, int MinYear = 1970, int MaxYear = 2100, int Limit = 10)
        {
            var db = DBContext.Create();
            var q = (from ci in db.CourseInstances
                    join c in db.Courses on ci.CourseID equals c.ID
                    where ( c.ID.Contains(Query) || c.Name.Contains(Query) || ci.ID.ToString().Contains(Query) ) &&
                    ci.Year >= MinYear && ci.Year <= MaxYear
                    select new { ci, c }).Take(Limit);
            return LinqHelper.GenericMap<CourseInstance>(q, "ci", "c>Course");
        }
    }
}